package com.axter.libs.photo.utils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.axter.libs.photo.R;
import com.axter.libs.photo.bean.MediaFolder;
import com.axter.libs.photo.bean.MediaInfo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 罗列图片视频文件工具类
 * Created by zhaobo on 2016/10/12.
 */

public class ListMediaUtils {
    private static final String MIME_TYPE_GIF = "image/gif";
    private boolean isContainGif;
    private boolean isContainVideo;
    private boolean isContainCamera;
    private String videoThumbDir;

    public ListMediaUtils(boolean isContainGif, boolean isContainVideo, boolean isContainCamera, String videoThumbDir) {
        this.isContainGif = isContainGif;
        this.isContainVideo = isContainVideo;
        this.isContainCamera = isContainCamera;
        this.videoThumbDir = videoThumbDir;
    }

    public List<MediaFolder> getData(Context appContext) {
        List<MediaFolder> allFolders = new ArrayList<>();
        List<MediaInfo> allImages = new ArrayList<>();

        // 获取图片
        List<MediaInfo> images = listAllImages(appContext, isContainGif);
        if (images != null) {
            allImages.addAll(images);
        }
        // 建立所有图片目录
        MediaFolder allFolder = new MediaFolder(appContext.getString(R.string.photoselect_images), allImages);
        allFolders.add(allFolder);

        if (isContainVideo) {
            // 获取视频
            List<MediaInfo> videos = listAllVideos(appContext);
            // 创建视频目录
            if (videos != null && videos.size() > 0) {
                allImages.addAll(videos);
                // 建立视频目录
                MediaFolder videoFolder = new MediaFolder(appContext.getString(R.string.photoselect_videos), videos);
                allFolders.add(videoFolder);
            }
        }

        // 全部排序,降序
        Collections.sort(allImages, new MediaInfo.SortImage());

        if (isContainCamera) {
            MediaInfo camera = new MediaInfo(MediaInfo.TYPE_CAMERA);
            allImages.add(0, camera);
        }

        List<MediaFolder> imageFolders = new ArrayList<>();
        for (MediaInfo image : images) {
            // 获取文件夹名称
            File folderFile = new File(image.getPath()).getParentFile();
            // 文件夹存在
            if (folderFile != null && folderFile.exists()) {
                MediaFolder f = getFolderByName(folderFile.getName(), imageFolders);
                if (f == null) {
                    MediaFolder folder = new MediaFolder(folderFile.getName(), image);
                    imageFolders.add(folder);
                } else {
                    f.add(image);
                }
            }
        }
        if (imageFolders != null && imageFolders.size() > 0) {
            allFolders.addAll(imageFolders);
        }
        return allFolders;
    }

    /**
     * 分类所有图片
     *
     * @param appContext
     * @param images       所有图片
     * @param isContainGif 是否包含gif图片
     * @return 图片目录分类
     */
    private List<MediaInfo> listAllImages(Context appContext, boolean isContainGif) {
        List<MediaInfo> images = new ArrayList<>();
        String[] projs = {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.TITLE,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.DATE_MODIFIED,
                MediaStore.Images.Media.SIZE
        };
        // 条件大小大于0  是否排除gif类型图片
        StringBuilder condition = new StringBuilder();
        condition.append(MediaStore.Images.Media.SIZE);
        condition.append(">0");
        if (!isContainGif) {
            condition.append(" and ");
            condition.append(MediaStore.Images.Media.MIME_TYPE);
            condition.append("<> 'image/gif'");
        }

        // 排序条件
        String sort = MediaStore.Images.Media.DATE_MODIFIED + " DESC";

        // 查询
        Cursor cursor = appContext.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projs, condition.toString(), null, sort);

        if (cursor == null || cursor.getCount() == 0) {
            return images;
        }
        cursor.moveToFirst();
        int titleColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.TITLE);
        int nameColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
        int mimeTypeColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.MIME_TYPE);
        int pathColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        int sizeColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
        int timeColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED);
        do {
            String title = cursor.getString(titleColumnIndex);
            String name = cursor.getString(nameColumnIndex);
            String mimeType = cursor.getString(mimeTypeColumnIndex);
            String path = cursor.getString(pathColumnIndex);
            long size = cursor.getLong(sizeColumnIndex);
            long time = cursor.getLong(timeColumnIndex);

            MediaInfo image;
            if (isFileExist(path)) {
                // 是否为动图
                if (isContainGif && MIME_TYPE_GIF.equals(mimeType)) {
                    image = new MediaInfo(MediaInfo.TYPE_IMAGE, title, name, mimeType, path, size, time);
                    image.setGif(true);
                } else {
                    image = new MediaInfo(MediaInfo.TYPE_IMAGE, title, name, mimeType, path, size, time);
                }
                images.add(image);
            }
        } while (cursor.moveToNext());
        return images;
    }

    private List<MediaInfo> listAllVideos(Context appContext) {
        List<MediaInfo> images = new ArrayList<>();
        String[] projs = {
                MediaStore.Video.Media.DATA,
                MediaStore.Video.Media.TITLE,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.MIME_TYPE,
                MediaStore.Video.Media.DATE_MODIFIED,
                MediaStore.Video.Media.SIZE,
                MediaStore.Video.VideoColumns.DURATION,
        };
        // 条件大小大于0
        StringBuilder condition = new StringBuilder();
        condition.append(MediaStore.Video.Media.SIZE);
        condition.append(" >0 ");
        condition.append(" and ");
        condition.append(MediaStore.Video.VideoColumns.DURATION);
        condition.append(" >0 ");

        // 排序条件
        String sort = MediaStore.Video.Media.DATE_MODIFIED + " DESC";

        // 查询
        Cursor cursor = appContext.getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projs, condition.toString(), null, sort);
        if (cursor == null || cursor.getCount() == 0) {
            return images;
        }
        cursor.moveToFirst();
        int titleColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE);
        int nameColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
        int mimeTypeColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.MIME_TYPE);
        int pathColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        int sizeColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
        int timeColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED);
        int durationColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.DURATION);
        do {
            String title = cursor.getString(titleColumnIndex);
            String name = cursor.getString(nameColumnIndex);
            String mimeType = cursor.getString(mimeTypeColumnIndex);
            String path = cursor.getString(pathColumnIndex);
            long size = cursor.getLong(sizeColumnIndex);
            long time = cursor.getLong(timeColumnIndex);
            long duration = cursor.getLong(durationColumnIndex);

            MediaInfo image;
            if (isFileExist(path)) {
                image = new MediaInfo(MediaInfo.TYPE_VIDEO, title, name, mimeType, path, size, time);
                image.setVideo(getVideoThumbPath(appContext, videoThumbDir, path, size, time), duration);
                images.add(image);
            }
        } while (cursor.moveToNext());
        return images;
    }

    private MediaFolder getFolderByName(String name, List<MediaFolder> folders) {
        if (folders != null) {
            for (MediaFolder folder : folders) {
                if (TextUtils.equals(folder.getTitle(), name)) {
                    return folder;
                }
            }
        }
        return null;
    }

    private boolean isFileExist(String path) {
        if (!TextUtils.isEmpty(path)) {
            return new File(path).exists();
        }
        return false;
    }

    private String getParentFileName(String data) {
        String filename[] = data.split("/");
        if (filename != null) {
            return filename[filename.length - 2];
        }
        return null;
    }

    public static void saveBitmapFile(Bitmap bm, String path) {
        try {
            File myCaptureFile = new File(path);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static String getVideoThumbPath(Context appContext, String videoThumbDir, String path, long size, long time) {
        // 生成视频缩略图
        if (TextUtils.isEmpty(videoThumbDir)) {
            videoThumbDir = appContext.getCacheDir().getAbsolutePath();
        }
        File dir = new File(videoThumbDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                dir = appContext.getCacheDir();
            }
        }
        String thumbPath = null;
        try {
            File thumbFile = new File(dir, (path + time + size).hashCode() + ".thumb");
            if (!thumbFile.exists()) {
                Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Images.Thumbnails.MINI_KIND);
                saveBitmapFile(bitmap, thumbFile.getAbsolutePath());
            }
            thumbPath = thumbFile.getAbsolutePath();
        } catch (Exception ex) {
            ex.printStackTrace();
            thumbPath = path;
        }
        return thumbPath;
    }
}
